package com.cn.nio.demo;

import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

@Slf4j
public class Service {

  public static void main(String[] args) {

    try {
      Selector selector = Selector.open();

      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.configureBlocking(false);
      serverSocketChannel.socket().bind(new InetSocketAddress(8080));
      serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
//      serverSocketChannel.register(selector, 0);

      // 只能声明一个 ServerSocketChannel
//      ServerSocketChannel serverSocketChannel1 = ServerSocketChannel.open();
//      serverSocketChannel1.configureBlocking(false);
//      serverSocketChannel1.socket().bind(new InetSocketAddress(8080));
//      serverSocketChannel1.register(selector, SelectionKey.OP_ACCEPT);

      log.info("start ...");
      while (true) {
        int selectNum = selector.select();
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()) {
          SelectionKey next = iterator.next();
          iterator.remove();

          if (next.isAcceptable()) {
            ServerSocketChannel newSocket = (ServerSocketChannel) next.channel();
            log.info("ServerSocketChannel -> {} -> {}", newSocket, newSocket.hashCode());
            SocketChannel acceptSocket = newSocket.accept();
            acceptSocket.configureBlocking(false);
            acceptSocket.register(selector, SelectionKey.OP_READ);
          } else if (next.isReadable()) {
            SocketChannel socketChannel = (SocketChannel) next.channel();
            ByteBuffer allocate = ByteBuffer.allocate(128);
            socketChannel.read(allocate);
            allocate.flip();
            log.info("request -> {}", new String(allocate.array(), StandardCharsets.UTF_8));
//            socketChannel.register(selector, SelectionKey.OP_WRITE);
//          } else if (next.isWritable()) {
//            SocketChannel socketChannel = (SocketChannel) next.channel();
            String s = new String("hello world，i`m server");
//            ByteBuffer allocate = ByteBuffer.allocate(128);
            allocate.put(s.getBytes(StandardCharsets.UTF_8));
            allocate.flip();
            socketChannel.write(allocate);
            socketChannel.close();
             int a_like = 1;
          } else {
            log.info("other selectkey ->{}", next);
          }

        }

      }

    } catch (IOException e) {
      e.printStackTrace();
    }


  }

}
